package com.abdd.hbxs_api.controller;

import com.abdd.hbxs_api.pojo.Userinfo;
import com.abdd.hbxs_api.service.UserinfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;


@Slf4j
@Controller
public class UserinfoController {

    @Autowired
    UserinfoService userinfoService;


    @RequestMapping("/test")
    @ResponseBody
    public String t(){
        return "t";
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    @ResponseBody
    public String login( String userName,  String userPassword){
        log.info("userName:{}", userName);
        log.info("userPassword:{}", userPassword);

        if(StringUtils.isEmpty(userName)){
            return "用户名不允许为空";
        }

        if(StringUtils.isEmpty(userPassword)){
            return "密码不允许为空";
        }

        Userinfo userinfo = userinfoService.findByName(userName);
        if(userinfo == null){
            return "用户不存在";
        }

        if(Objects.equals(userPassword, userinfo.getUserPassword())){
            return "登录成功";
        }

        if(!Objects.equals(userPassword, userinfo.getUserPassword())){
            return "密码错误";
        }

        return "登录失败";
    }

    @RequestMapping(value ="/register")
    @ResponseBody
    public String register(String userName, String userPassword){
        log.info("userName:{}", userName);
        log.info("userPassword:{}", userPassword);

        if(StringUtils.isEmpty(userName)){
            return "用户名不允许为空";
        }

        if(StringUtils.isEmpty(userPassword)){
            return "密码不允许为空";
        }

        Userinfo userinfo = userinfoService.findByName(userName);
        if(userinfo != null){
            return "用户名已存在！";
        }

        userinfo = new Userinfo(userName, userPassword);
        int resultCount = userinfoService.insert(userinfo);
        if(resultCount == 0){
            return "注册失败！";
        }

        return "注册成功";
    }

}
